package mysrpringboot.springboot.Service.impl;

import mysrpringboot.springboot.Dao.GoodsDao;
import mysrpringboot.springboot.Dao.OrderDao;
import mysrpringboot.springboot.Service.SellService;
import mysrpringboot.springboot.pojo.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.util.concurrent.TimeUnit;

@Service
public class SellServiceImpl implements SellService {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private GoodsDao goodsDao;

@Autowired
private OrderDao orderDao;
    @Override
    public int findNum() {
        Object num = redisTemplate.opsForValue().get("num");
        System.out.println(num);
        return (int) num;
    }

    @Override
    public void setKey() {
        redisTemplate.opsForValue().setIfAbsent("num", 100);
    }

    @Override
    public void updateNum(int num) {
        redisTemplate.delete("num");
        redisTemplate.opsForValue().setIfAbsent("num", num-1);
    }

    @Override
    public void expirsePay(String orderId) {
        redisTemplate.opsForValue().set("orderId", "orderId", 30, TimeUnit.SECONDS);
    }

    @Override
    public void saveGoods(Goods goods) {
        goodsDao.save(goods);
    }

    @Override
    public String findkey(String orderId) {

        while(redisTemplate.hasKey(orderId)){
            Object o = redisTemplate.opsForValue().get(orderId);
            redisTemplate.delete(orderId);

            Goods goods = new Goods();
            goods.setGoods_id(orderId);
            goods.setGoods_name("lagouphone");
            goodsDao.save(goods);
            return "支付成功";
        }
        return "抱歉，你没能及时支付";
    }

    @Override
    public void recovery(String key) {
        int num = orderDao.findNum();
        orderDao.update(num+1);
        updateNum(num+2);
    }
}
